<template>
  <div class="student-detail-container">
    <!-- 公共头部 -->

    <div class="detail-content">
      <!-- 学生信息卡片 -->
      <el-card class="student-card" v-if="studentInfo && !loading">
        <div class="student-header">
          <el-avatar :size="100" :src="studentInfo.user?.pic || defaultAvatar" class="student-avatar" />
          <div class="student-basic">
            <h2>{{ studentInfo.stuName || '未命名学生' }}</h2>
            <p class="student-id">用户ID: {{ studentInfo.userId }}</p>
            <p class="student-class">班级: {{ studentInfo.currentClass?.className || '未分配班级' }}</p>
            <!-- 添加班级下拉选择 -->
            <el-select 
              v-if="uniqueClasses.length > 1"
              v-model="studentInfo.currentClass"
              placeholder="选择班级"
              size="small"
              style="width: 200px; margin-top: 10px;"
              @change="handleClassChange"
            >
              <el-option
                v-for="cls in uniqueClasses"
                :key="cls.classId"
                :label="cls.className"
                :value="cls"
              />
            </el-select>
          </div>
        </div>
        
        <el-divider />
        
        <div class="student-stats">
          <div class="stat-item">
            <div class="stat-label">学习时长</div>
            <div class="stat-value">{{ formatStudyTime(studentInfo.stuStudyTime) }}</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-label">积分</div>
            <div class="stat-value">{{ studentInfo.stuScore || 0 }}分</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-label">出勤率</div>
            <div class="stat-value">{{ studentInfo.attendanceRate || 0 }}%</div>
          </div>
        </div>
      </el-card>
      
      <!-- 学习进度部分 -->
      <el-card class="progress-card" v-if="studentInfo && !loading">
        <template #header>
          <span>学习进度</span>
        </template>
        
        <el-progress 
          :percentage="calculateProgress(studentInfo.stuStudyTime)"
          :color="customColors"
          :stroke-width="16"
        />
        
        <div class="progress-details">
          <span>已完成: {{ Math.floor(studentInfo.stuStudyTime / 3600) }}小时</span>
          <span>目标: 100小时</span>
        </div>
      </el-card>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      
      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <el-alert
          title="获取学生信息失败"
          :description="error"
          type="error"
          show-icon
          closable
          @close="error = null"
        />
        <el-button type="primary" @click="fetchStudentDetail">重试</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import AppHeader from '@/components/AppHeader.vue'
import { getStudentDetailByUserId } from '@/api/auth'

const route = useRoute()
const studentInfo = ref({
  currentClass: null
})
const loading = ref(true)
const error = ref(null)
const defaultAvatar = ref('/src/assets/default-avatar.png')

// 从路由参数获取用户ID
const userId = ref(route.params.id)
console.log('当前学生ID:', userId.value)

const customColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

// 格式化学习时间
const formatStudyTime = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  return `${hours}小时${minutes}分钟`
}

// 计算学习进度百分比
const calculateProgress = (studyTime) => {
  const maxHours = 100 // 假设100小时为满进度
  const currentHours = studyTime / 3600
  return Math.min((currentHours / maxHours) * 100, 100)
}

// 处理班级选择变化
const handleClassChange = (selectedClass) => {
  studentInfo.value.currentClass = selectedClass
}

// 获取去重后的班级列表
const uniqueClasses = computed(() => {
  if (!studentInfo.value.classes) return []
  
  const uniqueMap = new Map()
  studentInfo.value.classes.forEach(cls => {
    if (!uniqueMap.has(cls.classId)) {
      uniqueMap.set(cls.classId, cls)
    }
  })
  return Array.from(uniqueMap.values())
})

// 获取学生详情
const fetchStudentDetail = async () => {
  try {
    loading.value = true
    error.value = null
    
    const response = await getStudentDetailByUserId(userId.value)
    console.log('完整API响应:', response)
    
    if (!response || !response.id) {
      throw new Error('未获取到学生信息')
    }
    
    // 处理响应数据
    studentInfo.value = {
      ...studentInfo.value,
      id: response.id,
      userId: response.userId,
      stuName: response.stuName,
      stuStudyTime: response.stuStudyTime || 0,
      stuScore: response.stuScore || 0,
      classes: response.classes || [],
      attendanceRate: response.attendanceRate || 0,
      user: {
        pic: response.user?.pic || defaultAvatar.value
      }
    }
    
    // 设置默认选中班级
    if (uniqueClasses.value.length > 0) {
      studentInfo.value.currentClass = uniqueClasses.value[0]
    }
    
    console.log('处理后的学生信息:', studentInfo.value)
    
  } catch (err) {
    console.error('获取学生详情失败:', {
      error: err,
      response: err.response?.data
    })
    error.value = err.message || '获取学生信息失败，请稍后再试'
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchStudentDetail()
})
</script>

<style scoped>
.student-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.detail-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.student-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.student-header {
  display: flex;
  align-items: center;
  padding: 20px;
}

.student-avatar {
  margin-right: 30px;
  border: 2px solid #eee;
}

.student-basic h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.student-id,
.student-class {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}

.student-stats {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.stat-item {
  text-align: center;
  min-width: 100px;
}

.stat-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.progress-card {
  margin-bottom: 20px;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.loading-container {
  padding: 40px;
  text-align: center;
}

.error-message {
  margin-top: 20px;
  text-align: center;
}

.error-message .el-button {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .student-header {
    flex-direction: column;
    text-align: center;
  }
  
  .student-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .student-stats {
    flex-direction: column;
    align-items: center;
  }
  
  .stat-item {
    margin-bottom: 20px;
  }
}
</style>